package dj.ms.support.feign;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.dj.common.exception.CentralRunException;
import com.dj.common.response.CentralResponse;
import com.dj.common.support.ExceptionHandler;
import feign.Response;
import feign.Util;
import feign.codec.ErrorDecoder;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.Charset;

/**
 * <br>
 * <p>
 * -
 * </p>
 *
 * <br>
 *
 * @author ZJG
 * @version 1.0
 * @date 2021/12/9 下午2:24
 */
@Slf4j
public class ExceptionErrorDecoder implements ErrorDecoder {

    @Override
    public Exception decode(String s, Response response) {
        try {
            if (response.body() != null) {
                String body = Util.toString(response.body().asReader(Charset.forName("UTF-8")));
                log.error(body);
                CentralResponse ei = JSON.parseObject(body, CentralResponse.class);
                if (ObjectUtil.isNotNull(ei)) {
                    CentralRunException businessException = ExceptionHandler.buildRunEx(reCode(ei), reMassage(ei.getMsg()));
                    return businessException;
                }
                String targetMsg= body.substring(body.lastIndexOf(":"),body.length());
                return ExceptionHandler.buildRunEx(targetMsg);
            }
        } catch (Exception var4) {
            log.error(var4.getMessage());
            return ExceptionHandler.buildRunEx(reMassage(var4.getMessage()));
        }
        return ExceptionHandler.buildRunEx("系统异常,请联系管理员");
    }

    private String reMassage(String body) {
        String msg = body;
        if (StrUtil.containsAny(body, "com.netflix.client.ClientException:", "Load balancer does not have available server for client")) {
            msg = body.substring(body.lastIndexOf(":") + 1) + "服务未找到";
        }
        if (StrUtil.containsAny(body, "FeignException", "InternalServerError", "{", "}")) {
            String targetMsg = body.substring(body.lastIndexOf("{"), body.lastIndexOf("}") + 1);
            CentralResponse ei = JSON.parseObject(targetMsg, CentralResponse.class);
            if (ObjectUtil.isNotNull(ei) ) {
                msg = ei.getMsg();
            }

        }
        return msg;
    }

    private int reCode(CentralResponse response) {
        String body = response.getMsg();
        if (StrUtil.containsAny(body, "feign", "FeignException", "InternalServerError", "{", "}")) {
            String targetMsg = body.substring(body.lastIndexOf("{"), body.lastIndexOf("}") + 1);
            log.error(targetMsg);
            CentralResponse ei = JSON.parseObject(targetMsg, CentralResponse.class);
            if (ObjectUtil.isNotNull(ei) ) {
                return ei.getCode();
            }
        }
        return response.getCode();
    }

}
